package com.corpgovernment.organization.controller.user;

import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.util.JsonUtil;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 导入功能controller
 *
 * @author wangyujue
 */
@RestController
@RequestMapping("/import")
public class ImportController {

    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
//    @Autowired
//    private IDepartmentInfoService departmentInfoService;

    private String SECRET_KEY = "";

    /**
     * 同步员工数据，只同步未删除的用户(DEL_FLAG = 0的数据)
     * post请求
     * MD5方式加密
     */
    @RequestMapping("/importEnterpriseUser")
    public String importEnterpriseUser(HttpServletRequest request) {


        // USER_ID	登录账号	VC2(60)	N	唯一键
        String uid = request.getParameter("uid");
        // USER_NAME	用户姓名	VC(60)	N
        String name = request.getParameter("name");
        // ORDER_INDEX	显示顺序	NUM(6)	N	在该部门内显示顺序
        // PASSWORD	登录口号	VC(64)	Y	加密存放
        // CLOSED	是否被注销	NUM(1)	N	0:激活；1:注销
        String valid = request.getParameter("valid");
        // DEPT_ID	主部门ID	VC2(32)	N
        String orgId = request.getParameter("orgId");
        // ROLE_ID	主角色ID	VC2(32)	Y
        // IS_MANAGER	是否管理者	NUM(1)	Y
        // MOBILE	手机号码	VC2(30)	Y
        String mobilePhone = request.getParameter("mobilePhone");
        // EMAIL	电子邮件	VC2(100)	Y
        String email = request.getParameter("email");
        // DEL_FLAG	删除标识	VC2(2)	N	0:有效；1:已删除
        String isDeleted = request.getParameter("isDeleted");
        // 加密串
        String checkStr = request.getParameter("checkStr");


        if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(name) || StringUtils.isEmpty(valid)
                || StringUtils.isEmpty(orgId) || StringUtils.isEmpty(mobilePhone) || StringUtils.isEmpty(email) || StringUtils.isEmpty(isDeleted)
                || StringUtils.isEmpty(checkStr)) {
            return error(-1, "参数异常");
        }

        Map<String, String> paramMap = new TreeMap<>();
        paramMap.put("uid", uid);
        paramMap.put("name", name);
        paramMap.put("valid", valid);
        paramMap.put("orgId", orgId);
        paramMap.put("mobilePhone", mobilePhone);
        paramMap.put("email", email);

        String enctryptedStr = hmacMd5(getParamByKeyOrder(paramMap), SECRET_KEY);

        if (!enctryptedStr.equals(checkStr)) {
            return error(-2, "参数校验失败");
        }

        // todo 手机号是否有-，国家码？

        // uid验重
        MbOrgEmployeeInfo dbUserInfo = organizationEmployeeService.findByUid(uid);
        if (dbUserInfo != null) {
            return error(-4, "uid重复");
        }

        // orgId验证组织架构数据是否存在
        MbOrgInfo dbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (dbOrgInfo == null) {
            return error(-4, "用户所在组织结构不存在");
        }

        MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
        mbOrgEmployeeInfo.setUid(uid);
        mbOrgEmployeeInfo.setName(name);
        // todo 密码是否需要打通
        mbOrgEmployeeInfo.setValid(valid);
        mbOrgEmployeeInfo.setOrgId(orgId);
        mbOrgEmployeeInfo.setMobilePhone(mobilePhone);
        mbOrgEmployeeInfo.setEmail(email);
        // 默认中国
        mbOrgEmployeeInfo.setNationality("CN|中国大陆");
        mbOrgEmployeeInfo.setIsBackground(false);
        // todo 默认男？
        mbOrgEmployeeInfo.setGender("M");
        organizationEmployeeService.create(mbOrgEmployeeInfo);
        return success();
    }


    /**
     * 同步组织架构数据，只同步未删除的用户(DEL_FLAG = 0的数据)
     * post请求
     * MD5方式加密
     */
    @RequestMapping("/importOrganization")
    public String importOrganization(HttpServletRequest request) {


        // ID	主键	VC(32)	N	PK
        String orgId = request.getParameter("orgId");
        // PARENT_DEPTID	上级部门ID	VC(32)	Y	顶级部门时空
        String parentId = request.getParameter("parentId");
        // DEPT_NAME	部门名称	VC(100)	N
        String name = request.getParameter("name");
        // DEPT_NO	部门编码	VC2(60)	Y
        String departmentCode = request.getParameter("departmentCode");
        // ORDER_INDEX	显示顺序	NUM(6)	Y	同父级部门下的显示顺序
        String order = request.getParameter("order");
        // LAYER	部门层级	NUM(3)	Y	数字如：1、2、3
        String level = request.getParameter("level");
        // type D:部门  C:公司
        String type = request.getParameter("type");
        // ADMINISTRATORS	部门管理员	VC2(200)	Y	多个管理员以空格分隔
        String leader = request.getParameter("leader");
        // CLOSED	是否注销	VC2(2)	N	0:活跃；1:注销
        String valid = request.getParameter("valid");


        // DEL_FLAG	删除标识	VC2(2)	N	0:有效；1:已删除
        String isDeleted = request.getParameter("isDeleted");
        // 加密串
        String checkStr = request.getParameter("checkStr");


        if (StringUtils.isEmpty(orgId)
                || StringUtils.isEmpty(parentId)
                || StringUtils.isEmpty(name)
                || StringUtils.isEmpty(departmentCode)
                || StringUtils.isEmpty(order)
                || StringUtils.isEmpty(level)
                || StringUtils.isEmpty(type)
                || StringUtils.isEmpty(leader)
                || StringUtils.isEmpty(valid)
                || StringUtils.isEmpty(isDeleted)
                || StringUtils.isEmpty(checkStr)) {
            return error(-1, "参数异常");
        }

        Map<String, String> paramMap = new TreeMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("parentId", parentId);
        paramMap.put("name", name);
        paramMap.put("departmentCode", departmentCode);
        paramMap.put("order", order);
        paramMap.put("level", level);
        paramMap.put("type", type);
        paramMap.put("leader", leader);
        paramMap.put("valid", valid);
        String enctryptedStr = hmacMd5(getParamByKeyOrder(paramMap), SECRET_KEY);

        if (!enctryptedStr.equals(checkStr)) {
            return error(-2, "参数校验失败");
        }

        // orgId验重
        MbOrgInfo dbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (dbOrgInfo != null) {
            return error(-4, "组织架构重复");
        }

        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(orgId);
        mbOrgInfo.setParentId(parentId);
        mbOrgInfo.setName(name);
        mbOrgInfo.setOrderNum(Integer.valueOf(order));
        mbOrgInfo.setLevel(Integer.valueOf(level));
        mbOrgInfo.setOrgType(type);
        mbOrgInfo.setValid(valid);
        organizationInfoService.createOrgInfo(mbOrgInfo);
        return success();
    }

    public static String getParamByKeyOrder(Map<String, String> map) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key).append("=").append(value).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String hmacMd5(String value, String key) {
        try {
            // Get an hmac_sha1 key from the raw key bytes
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacMD5");

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(value.getBytes());

            // Convert raw bytes to Hex
            byte[] hexBytes = new Hex().encode(rawHmac);

            //  Covert array of Hex bytes to a String
            return new HexBinaryAdapter().marshal(rawHmac);
//            return new String(hexBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * -1：参数异常
     * -2：验签失败
     * -3：重复订单
     *
     * @param code
     * @param msg
     * @return
     */
    public String error(int code, String msg) {
        Map map = new HashMap();
        map.put("status", 200);
        map.put("errorCode", code);
        map.put("errorMsg", msg);
        map.put("rt", "error");
        return JsonUtil.toJson(map);
    }

    public String success() {
        Map map = new HashMap();
        map.put("status", 200);
        map.put("errorCode", 0);
        map.put("errorMsg", "");
        map.put("rt", "success");
        return JsonUtil.toJson(map);
    }
}
